

import { Workbook } from 'exceljs'
import { saveAs } from 'file-saver'



/**
 * @description 导出xlsx
 * @param {*} fileName String xlsx的文件名
 * @param {*} xlsxList Array
 * 
 *     [
        {
            sheetName: '', // 页签 （默认Sheet 1.....）
            titleObj: { // 表格标题（不写不展示）
                name: '',
                merge: '', // 合并的单元格 merge：A1:P1
            },
            rows: [], // 表格数据
            columns: [], // 表头 [{name: 'xxx'}]
            mergeOptions: [
                {
                    merge: '', // 合并的单元格 A2:A3
                    value: '' // 单元格名称 不属于表格的数据的合并 展示的名称
                }
            ],
            ref: '' // 表格的数据左上角 ref: A3
        }
    ]
 * 
 * 
 * @param {*} pageSetup Object 页面的基础设置配置
 *   pageSetup: {
        horizontalCentered: false,  // 是否将工作表数据水平居中
        verticalCentered: false, // 是否将工作表数据垂直居中
        defaultRowHeight： 15 // 默认行高
        appointRowHeight: [{_number: 1, height:50, }] 指定row的行高 
        cellWidthCollections: [{index: 列号，width}] 指定列的宽度
    }
 * 
 */


export function handleExcel(fileName = '', pageSetup = {}, xlsxList = []) {
    return new Promise(async (resolve, reject) => {
        if (Array.isArray(xlsxList)) {
            const workbook = new Workbook() // 文件簿实例
            xlsxList.map((v, i) => {
                const { titleObj = {}, sheetName = '', mergeOptions = [], columns = [], rows = [], ref = 'A1' } = v
                let sheet = ''
                if (sheetName.replace(/\s*/g, "") !== '') {
                    sheet = workbook.addWorksheet(sheetName);
                } else {
                    sheet = workbook.addWorksheet(`Sheet${index + 1}`);
                }
                // sheet.properties.defaultColWidth = 14
                if (titleObj.name.replace(/\s*/g, "") !== '') {
                    const Sparecarcell = sheet.getCell(`A1`);
                    sheet.mergeCells(`${titleObj.merge}`);
                    Sparecarcell.value = `${titleObj.name}`
                    Sparecarcell.font = { name: '宋体', family: 4, size: 14, bold: true }; // 字体
                    Sparecarcell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };//对齐
                }
                if (mergeOptions.length) {
                    mergeOptions.map((m, mi) => {
                        sheet.mergeCells(`${m.merge}`);
                        if (m.value) {
                            const Sparecarcell_ = sheet.getCell(`${m.merge.split(':')[0]}`);
                            Sparecarcell_.value = m.value
                        }
                    })
                }
                if (pageSetup.cellWidthCollections?.length) {
                    pageSetup.cellWidthCollections.map(v => {
                        sheet.getColumn(v.index).width = v.width
                    })
                }
                
                sheet.addTable({
                    name: 'naturalTable',
                    ref,
                    columns,
                    style: {
                        theme: 0
                    },
                    rows
                });
                // 设置页面的配置、文档的页面配置项不支持pageSetup
                if (pageSetup.horizontalCentered || pageSetup.verticalCentered) {

                    sheet.eachRow(function (row) {
                        // 指定行高
                        const heightArr = pageSetup.appointRowHeight.filter(v => v._number === row._number)
                        if (heightArr.length) {
                            row.height = heightArr[0].height
                        } else {
                            pageSetup.defaultRowHeight && (row.height = pageSetup.defaultRowHeight)
                        }
                        row.alignment = { vertical: pageSetup.verticalCentered ? 'middle' : '', horizontal: pageSetup.horizontalCentered ? 'center' : '', wrapText: true }
                    });
                }
            })

            const buffer = await workbook.xlsx.writeBuffer()

            let blob = new Blob([buffer], {
                type: 'application/octet-stream'
            })
            saveAs(blob, `${fileName}.xlsx`);
            resolve()
        } else {
            reject(xlsxList类型不对)
        }
    })

}